package jvm;

import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定义一个 Classloader，加载一个 Hello.xlass 文件，执行 hello 方法，此文件内容是一个 Hello.class 文件所有字节（x=255-x）处理后的文件。文件群里提供。
 * 经过测试。Hello前面没有包名jvm
 */
public class HelloClassLoader extends ClassLoader {

    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> clazz = new HelloClassLoader().findClass("Hello");
        Object o = clazz.newInstance();
        Method hello = clazz.getDeclaredMethod("hello");
        hello.setAccessible(true);
        hello.invoke(o);
    }

    private byte[] loadByte() throws Exception {
        FileInputStream fis = new FileInputStream("01Jvm/jvm/Hello.xlass");
        int len = fis.available();
        byte[] data = new byte[len];
        fis.read(data);
        fis.close();
        return data;
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] data = new byte[0];
        try {
            data = loadByte();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        byte[] bytes = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            //255-  可用byte计算，-1-
            bytes[i] = (byte) (-1 - data[i]);
        }
        return defineClass(name, bytes, 0, bytes.length);
    }
}
